﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Win.CSkin.Test.ISHIDA
{
    public class Printer_ISHIDA
    {
        AxL2KCTRLLib.AxL2kctrl LabelPriter;
        DateTime printStartTime = DateTime.Now;
        private string _PrinterName;
        private string _Port;
        private string _Mode;

        /// <summary>
        /// 打印机实体化
        /// </summary>
        /// <param name="PrinterName">ISHIDA L-1000-12</param>
        /// <param name="Port">USB001</param>
        /// <param name="Mode">3</param>
        public Printer_ISHIDA(string PrinterName, string Port, string Mode)
        {
            _PrinterName = PrinterName;
            _Port = Port;
            _Mode = Mode;
            LabelPriter = new AxL2KCTRLLib.AxL2kctrl();
            LabelPriter.CreateControl();
            LabelPriter.RTIME = 3000;   //3S
            LabelPriter.WTIME = 3000;   //3S
            LabelPriter.Mode = 0;       //TCP
        }

        /// <summary>
        /// 获取标签打印机的运行状态
        /// </summary>
        /// <param name="progresspages">剩余发行数</param>
        /// <param name="state">打印机状态字符串</param>
        /// <returns></returns>
        public long GetLabelPrinterState(out int progresspages, out string state, out string ErrInfo)
        {
            long lrc = 3; // G_IS_ErrorCode.LabelPrinter_Error_Connect;
            ErrInfo = string.Empty;
            bool opend = false;
            string strStatus;
            int value;

            progresspages = 0;
            state = "";
            //故障失败后重试的次数
            int retryCount = 1;
            do
            {
                try
                {
                    do
                    {
                        //重置打开状态标识。
                        opend = false;
                        DateTime startTime = DateTime.Now;
                        while (startTime.AddSeconds(15).CompareTo(DateTime.Now) > 0 && opend == false)
                        {
                            //由于打印队列有打开打印机端口的可能性，
                            //重复打印机最多打开15秒
                            LabelPriter.Mode = short.Parse(_Mode);
                            opend = LabelPriter.Open(_Port, "", "");
                            System.Threading.Thread.Sleep(100);
                        }
                        if (!opend)
                        {

                            ErrInfo = "打印机打开失败!  " + TraceEventType.Error;
                            //打印机打开故障时不要重试。
                            retryCount = 0;
                            break;
                        }
                        System.Threading.Thread.Sleep(200);
                        strStatus = LabelPriter.GetStatusStr();
                        if (strStatus == null || strStatus == "" || strStatus.Length != 14)
                        {   //无法正确获得打印机状态
                            break;
                        }
                        //剩余发行和状态解析
                        //--- 获取剩余发行数目
                        progresspages = Convert.ToInt32(strStatus.Substring(3, 6));
                        //--- 状态码数字化字符串（十六进制数）
                        value = Convert.ToInt32(strStatus.Substring(9, 4), 16);
                        if ((value & 0x01000) != 0)
                        {   //错误如下
                            if ((value & 0x00010) != 0)
                            {   //标签结束（标签耗尽）错误
                                state = "印字标签的尺寸不恰当或标签纸用完。请确认标签的装填。";
                            }
                            else if ((value & 0x00020) != 0)
                            {   //色带耗尽错误
                                state = "印字色带用完。请换色带。";
                            }
                            else if ((value & 0x00040) != 0)
                            {   //打印机头打开错误
                                state = "打印机头打开报错。请确认打印机头的状态。";
                            }
                            else if ((value & 0x00080) != 0)
                            {   //打印机头损坏错误
                                state = "打印机头破损。请确认打印机头的状态。";
                            }
                            else if ((value & 0x00002) != 0)
                            {   //打印机切割动作错误
                                state = "打印机的切割动作的报错被检知。请确认打印机的状态。";
                            }
                            else
                            {   //其他错误
                                state = "打印机报错被检知（详细原因不明）。请确认打印机的状态。";
                            }
                        }
                        else if ((value & 0x04000) != 0)
                        {   //离线
                            state = "打印机处于离线状态。请确认打印机的状态。";
                        }
                        else if ((value & 0x00800) != 0)
                        {   //给打印页面计数
                            progresspages++;
                        }
                        lrc = 0; // G_IS_ErrorCode.OK;
                    } while (false);
                }
                catch (Exception ex)
                {
                    ErrInfo = ex.Message;
                    lrc = 3; // G_IS_ErrorCode.LabelPrinter_Error_Connect;
                }
                if (opend)
                {
                    bool brc = false;
                    brc = LabelPriter.Close();
                    int waitTime = 0;
                    while (brc == false && waitTime < 300)
                    {
                        //进程挂起0.1秒
                        System.Threading.Thread.Sleep(100);
                        brc = LabelPriter.Close();
                        waitTime += 100;
                    }
                    printStartTime = DateTime.Now;
                }
                //获取成功，跳出循环
                if (lrc == 0) //G_IS_ErrorCode.OK
                    break;

                if (retryCount <= 0)
                    break;

                //如果不能获取打印机状态，重试。
                ErrInfo = "打印机状态获取重试  " + TraceEventType.Information;
                retryCount--;
                System.Threading.Thread.Sleep(3000);    //3秒待機
            } while (true);
            return lrc;
        }

    }
}
